package com.spic.system.service.impl;

import com.spic.common.core.exception.ServiceException;
import com.spic.common.core.utils.DateUtils;
import com.spic.system.domain.SysNumberConfig;
import com.spic.system.domain.SysNumberConfig.Cycle;
import com.spic.system.domain.SysNumberHistory;
import com.spic.system.mapper.SysNumberConfigMapper;
import com.spic.system.mapper.SysNumberHistoryMapper;
import com.spic.system.service.ISysNumberConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 流水号规则配置Service业务层处理
 * 
 * @author spic
 * @date 2021-11-02
 */
@Service
public class SysNumberConfigServiceImpl implements ISysNumberConfigService 
{
    @Autowired
    private SysNumberConfigMapper sysNumberConfigMapper;
    @Autowired
    private SysNumberHistoryMapper historyMapper;
    /**
     * 查询流水号规则配置
     * 
     * @param id 流水号规则配置主键
     * @return 流水号规则配置
     */
    @Override
    public SysNumberConfig selectSysNumberConfigById(Long id)
    {
        return sysNumberConfigMapper.selectSysNumberConfigById(id);
    }

    /**
     * 查询流水号规则配置列表
     * 
     * @param sysNumberConfig 流水号规则配置
     * @return 流水号规则配置
     */
    @Override
    public List<SysNumberConfig> selectSysNumberConfigList(SysNumberConfig sysNumberConfig)
    {
        return sysNumberConfigMapper.selectSysNumberConfigList(sysNumberConfig);
    }

    /**
     * 新增流水号规则配置
     * 
     * @param sysNumberConfig 流水号规则配置
     * @return 结果
     */
    @Override
    public int insertSysNumberConfig(SysNumberConfig sysNumberConfig)
    {
        sysNumberConfig.setCreateTime(DateUtils.getNowDate());
        return sysNumberConfigMapper.insertSysNumberConfig(sysNumberConfig);
    }

    /**
     * 修改流水号规则配置
     * 
     * @param sysNumberConfig 流水号规则配置
     * @return 结果
     */
    @Override
    public int updateSysNumberConfig(SysNumberConfig sysNumberConfig)
    {
        sysNumberConfig.setUpdateTime(DateUtils.getNowDate());
        return sysNumberConfigMapper.updateSysNumberConfig(sysNumberConfig);
    }

    /**
     * 批量删除流水号规则配置
     * 
     * @param ids 需要删除的流水号规则配置主键
     * @return 结果
     */
    @Override
    public int deleteSysNumberConfigByIds(Long[] ids)
    {
        int count = historyMapper.getCountByNumberConfigIds(ids);
        if(count > 0) throw new ServiceException("已有历史流水号，不呢删除");
        return sysNumberConfigMapper.deleteSysNumberConfigByIds(ids);
    }

    /**
     * 删除流水号规则配置信息
     * 
     * @param id 流水号规则配置主键
     * @return 结果
     */
    @Override
    public int deleteSysNumberConfigById(Long id)
    {
        return sysNumberConfigMapper.deleteSysNumberConfigById(id);
    }

    @Override
    public boolean checkCodeNameUnique(String codeName) {
        SysNumberConfig sys = new SysNumberConfig();
        sys.setCodename(codeName);
        List<SysNumberConfig> configs = sysNumberConfigMapper.selectSysNumberConfigList(sys);
        if(CollectionUtils.isEmpty(configs)) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String getCode(String codeName) {
        SysNumberConfig sys = new SysNumberConfig();
        sys.setCodename(codeName);
        List<SysNumberConfig> configs = sysNumberConfigMapper.selectSysNumberConfigList(sys);
        if(configs.size() < 1) throw new ServiceException("没有相应的code");
        SysNumberConfig config = configs.get(0);
        SysNumberHistory history = historyMapper.selectByConfig(config);
        return compose(config, history);
    }

    private String compose(SysNumberConfig config, SysNumberHistory history) {
        Long maxVal = null;
        LocalDate now = LocalDate.now();
        if(history == null){
            maxVal = config.getStartnumber();
            history = new SysNumberHistory();
            BeanUtils.copyProperties(config, history);
            history.setId(null);
            history.setMaxNumber(config.getStartnumber());
            history.initDate(now);
            historyMapper.insertSysNumberHistory(history);
        }
        maxVal = history.getMaxNumber();
        boolean isNewCycle = isNewCycle(config, history);
        if(isNewCycle){
            history.setMaxNumber(config.getStartnumber());
            maxVal = config.getStartnumber();
        }
        history.initDate(now);
        history.setMaxNumber(maxVal+config.getStep());
        history.setUpdateTime(new Date());
        historyMapper.updateSysNumberHistory(history);
        StringBuilder result = new StringBuilder(config.getPrefix());
        result.append(composeInfix(config.getInfix()));
        result.append(composeVal(maxVal, config.getDigit()));
        result.append(config.getSuffix());
        return result.toString();
    }


    /** 是否进入下一个序号新周期
     * @param config
     * @param history
     * @return
     */
    private boolean isNewCycle(SysNumberConfig config, SysNumberHistory history) {
        Cycle cycle = config.getCycle();
        LocalDate now = LocalDate.now();
        if(Cycle.NONE.equals(cycle) || Objects.isNull(cycle)) return false;
        if(Cycle.YEAR.equals(cycle)){
            if(history.getYear() < now.getYear()) return true;
        }
        if(Cycle.MONTH.equals(cycle)){
            if(history.getYear() < now.getYear() || history.getMonth() < now.getMonthValue()) return true;
        }
        if(Cycle.DAY.equals(cycle)){
            if(history.getYear() < now.getYear() || history.getMonth() < now.getMonthValue()
                    || history.getDay() < now.getDayOfMonth() ) {
                return true;
            }
        }
        return false;
    }

    //序号填充空位
    private String composeVal(Long maxVal, Integer digit) {
        int valDigit =  maxVal.toString().length();
        int differenceVal = digit - valDigit;
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < differenceVal; i++) {
            result.append("0");
        }
        return result.append(maxVal).toString();
    }

    //日期中缀转换
    private String composeInfix(String infix) {
        if (infix == null || infix.equals("") || infix.equals("null")) {
            return "";
        }
        return new SimpleDateFormat(infix).format(new Date());
    }

}
